﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上提供

namespace SplitViewOptions
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class PictureImagePage : Page
    {
        public PictureImagePage()
        {
            this.InitializeComponent();
        }
        List<InMemoryRandomAccessStream> liststream = new List<InMemoryRandomAccessStream>();
        List<Stream>  liststreampic= new List<Stream>();
        List<byte[]> listbytes = new List<byte[]>();
        List<BitmapImage> listbmp = new List<BitmapImage>();
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                
                if (App.Isdownloadstirngmode)
                {
                    pictureviewer.ItemsSource = App.Picurllist;
                }
                else
                {
                    App.Picurllist = await HtmlUsedFunction.getallimageByhtmlstring(await HtmlUsedFunction.gethtmlstring(App.Currenturl.AbsoluteUri));
                    Debug.WriteLine(App.Picurllist.Count + "App.picurllist");
                    await App.showmessage("获取到"+ App.Picurllist.Count+"个",100);
                    foreach (var a in App.Picurllist)
                    {
                        if (string.IsNullOrEmpty(a)) continue;
                        if (!a.StartsWith("http")) continue;
                        var myClient = new HttpClient();
                        Stream memorystream = await myClient.GetStreamAsync(a);
                       
                        BitmapImage bmp = new BitmapImage();
                        var randomAccessStream = new InMemoryRandomAccessStream();

                        var outputStream = randomAccessStream.GetOutputStreamAt(0);

                        await RandomAccessStream.CopyAsync(memorystream.AsInputStream(), outputStream);
                        //InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                        await App.showmessage("下载第" + App.Picurllist.IndexOf(a) + "个", 36);
                        //DataWriter datawriter = new DataWriter(randomAccessStream.GetOutputStreamAt(0));

                        //datawriter.WriteBytes(bytes);

                        //  await datawriter.StoreAsync();
                        //memorystream.Dispose();
                        liststreampic.Add(memorystream);
                      //  liststream.Add(randomAccessStream);

                        await bmp.SetSourceAsync(randomAccessStream);
                        //memorystream.Dispose();
                        //randomAccessStream.Dispose();
                        listbmp.Add(bmp);

                    }
                    pictureviewer.ItemsSource = listbmp;

                }
                base.OnNavigatedTo(e);
            }catch(Exception EX)
            {

            }
        }
        private void Border_Tapped(object sender, TappedRoutedEventArgs e)
        {

        }

        private void baack_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.GoBack();
        }

        private async void savebtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BitmapImage bmpfd = pictureviewer.SelectedItem as BitmapImage;

                Random pne = new Random();
                int jk = pne.Next(1, 100000000);
                WriteableBitmap wbmp = new WriteableBitmap(300, 300);
                int i = listbmp.IndexOf(bmpfd);
                var myClient = new HttpClient();
                Stream memorystream = await myClient.GetStreamAsync(new Uri(App.Picurllist.ElementAt(i), UriKind.Absolute));

                var memStream = new MemoryStream();
                await memorystream.CopyToAsync(memStream);
                memStream.Position = 0;
                //Image obj = ((pictureviewer.ContainerFromIndex(i) as GridViewItem).ContentTemplateRoot as Border).Child as Image;
                //Stream onemm = liststreampic.ElementAt(i);
                //// onemm.Position = 0;
                //RenderTargetBitmap render = new RenderTargetBitmap();
                //await render.RenderAsync(obj);
                //IBuffer ibuffer = await render.GetPixelsAsync();
                //IRandomAccessStream memStream = ibuffer.AsStream().AsRandomAccessStream();
                //   memStream.Position = 0;

                await wbmp.SetSourceAsync(memStream.AsRandomAccessStream());
                await SaveToPngImage(wbmp, PickerLocationId.PicturesLibrary, "多彩浏览器" + jk.ToString());
            }
            catch(Exception exxx)
            {

            }
            return;
            //IList<BitmapImage>   selectedbmps=  pictureviewer.SelectedItems as IList<BitmapImage>;
            //List<int> selectedindexlist = new List<int>();
            //IReadOnlyList<ItemIndexRange> selecte = pictureviewer.SelectedRanges;
            //for(int i=0;i<selecte.Count;i++)
            //{
            //    ItemIndexRange oneitem = selecte.ElementAt(i);
            //    selectedindexlist.Add(oneitem.FirstIndex);
            //}
            // for (int j = 0; j < selectedindexlist.Count; j++)
            //{
            //     int k = selectedindexlist.ElementAt(j);
            //     //Stream selectestream = liststreampic.ElementAt(k);
            //     //MemoryStream meno = new MemoryStream();
            //     //Stream testsream=null;   selectestream.CopyTo(meno);
            //    BitmapImage onebmp = selectedbmps.ElementAt(k);
            //     Random pne = new Random();
            //     int jk = pne.Next(1, 100000000);
            //     WriteableBitmap wbmp = new WriteableBitmap(onebmp.PixelWidth, onebmp.PixelHeight);
            //     await SaveToPngImage(wbmp,PickerLocationId.PicturesLibrary, "多彩浏览器器"+j.ToString()+ jk.ToString());
            //     //wbmp.
            //     //wbmp.SaveJpeg(stream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 85);
            //     //Wbmp = wbmp;

            //     // var buffer = new Windows.Storage.Streams.Buffer((uint)selectestream.Size);
            //     // selectestream.Seek(0);
            //     //var ibuffer = await selectestream.ReadAsync(buffer, (uint)selectestream.Size, Windows.Storage.Streams.InputStreamOptions.None);
            //     // selectestream.Dispose();

            //     //  await SaveImage(resultbyte, listbmp.ElementAt(k).PixelWidth, listbmp.ElementAt(k).PixelHeight);
            // }
            await App.showmessage("截图保存到图片库");
            // MessageDialog one = new MessageDialog("截图保存到图片库");
            //await one.ShowAsync();

        }
        public  async Task<FileUpdateStatus> SaveToPngImage( WriteableBitmap bitmap, PickerLocationId location, string fileName)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };
            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);


                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    Stream pixelStream = bitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                              (uint)bitmap.PixelWidth,
                              (uint)bitmap.PixelHeight,
                              96.0,
                              96.0,
                              pixels);
                    await encoder.FlushAsync();
                }


                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
        public byte[] ConvertStreamTobyte(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
        private async Task SaveImage(byte[] bytes, int width,int height)
        {
            //Rendu du composant Xaml, ici le graphique 'Syncfusion.Chart', sous forme d'image en mémoire.
           // RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            //await renderTargetBitmap.RenderAsync(doughnutMadelin, (int)myDoughnutActualWidth, (int)myDoughnut.ActualHeight);
            // var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

            var localFolder = Windows.Storage.KnownFolders.PicturesLibrary;
            Random randon = new Random();
            string filepicname = "fdfdafadfdf";
            //  var localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var saveFile = await localFolder.CreateFileAsync(filepicname + ".jpeg", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            // Encodage de l'image en mémoire dans le fichier désigné sur le disque
            using (var fileStream = await saveFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);
                double dpx = DisplayInformation.GetForCurrentView().LogicalDpi;
                double dpy = DisplayInformation.GetForCurrentView().LogicalDpi;
                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)width,
                    (uint)height,
              36,
               36,
                  bytes);

                await encoder.FlushAsync();
            }
         

        }

        private async  void saveallbtn_Click(object sender, RoutedEventArgs e)
        {
            foreach(var a in App.Picurllist.Distinct())
            {
                if(a.StartsWith ("http"))
                {
                    Uri source = new Uri(a,UriKind.RelativeOrAbsolute);
                    Random randow = new Random();

                    string destination ="duocai"+ randow.Next(1, 100000).ToString() + ".jpg";

                    StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                        destination, CreationCollisionOption.GenerateUniqueName);

                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                    await download.StartAsync();
                    await App.showmessage("保存第" + App.Picurllist.IndexOf(a) + "个", 10);
                  //  picstackpanel.Visibility = Visibility.Collapsed;
                }
            }
            await App.showmessage("全部保存完成");
            allsavebtn.Content = "全部保存完成";
        }

        private async void duoxuansavebtn_Click(object sender, RoutedEventArgs e)
        {
            IReadOnlyList<ItemIndexRange> moreselectindex = pictureviewer.SelectedRanges;
           // Debug.WriteLine(moreselectindex.Count);
            foreach (var a in moreselectindex)
            {
                Debug.WriteLine(a.FirstIndex + "firstindex");
                Debug.WriteLine(a.LastIndex + "LastIndex");
                Debug.WriteLine(a.Length + "Length");
                for(int i = a.FirstIndex; i <= a.LastIndex; i++)
                {
                  string morestr=  App.Picurllist.ElementAt(i);
                    if (morestr.StartsWith("http"))
                    {
                        string destination = string.Empty;
                        Uri source = new Uri(morestr, UriKind.RelativeOrAbsolute);
                        Random randow = new Random();
                        if (morestr.Contains(".jpg") || morestr.Contains(".gif") || morestr.Contains(".jpeg") || morestr.Contains(".png"))
                        {
                            if (morestr.Contains(".gif"))
                            {
                                destination = "duocai" + randow.Next(1, 100000).ToString() + ".gif";
                            }
                            else if (morestr.Contains(".png"))
                            {
                                destination = "duocai" + randow.Next(1, 100000).ToString() + ".png";
                            }
                            else
                            {
                                destination = "duocai" + randow.Next(1, 100000).ToString() + ".jpg";
                            }
                        }
                        else
                        {
                            destination = "duocai" + randow.Next(1, 1000000).ToString() + ".jpg";
                        }
                       // = "duocai" + randow.Next(1, 100000).ToString() + ".jpg";
                        StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                            destination, CreationCollisionOption.GenerateUniqueName);

                        BackgroundDownloader downloader = new BackgroundDownloader();
                        DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                        await download.StartAsync();
                    }
                        
                }
            }
            await App.showmessage("保存完成");
            duoxuansavebtn.Content = "保存完成";
        }
    }
}
